package com.agv.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.agv.core.dao.IGridPojoDao;
import com.agv.core.exception.AgvException;
import com.agv.core.objectDomain.Usuario;
import com.agv.core.util.GridPojo;

public class TrnGenericShowGridsAction extends Action{
	
	public ActionForward execute(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response)throws AgvException{
		
		
		String nombreDao  = request.getParameter("beanDao");
		String forward = "";
		
		Object[] params = null;
		GridPojo pojo = new GridPojo();
		
		WebApplicationContext springCtx = WebApplicationContextUtils.getWebApplicationContext( this.getServlet().getServletContext() );
		IGridPojoDao dao =  (IGridPojoDao)springCtx.getBean(nombreDao);
		
		
		if( request.getParameter("idbean") == null  ){ //entramos por primera vez 
			
			Usuario user = (Usuario) request.getSession().getAttribute("usuarioObj");
		    int idOrg = user.getIdUsuario();
			
		    params = new Object[]{idOrg};
			forward = "gridpojo";
			
			pojo = dao.findFirstGrid(params);
			pojo.setUrlSegundoGrid("trnGrids.do?beanDao="+nombreDao);
			
		}else{
			
			//se instancia el dao de la tabla secundaria
			String nombrePK = request.getParameter("nombrePk");
			String valorPK = request.getParameter(nombrePK);
			
			params = new Object[]{valorPK};
			
			pojo  = dao.findSecondGrid(params);
			pojo.setNombreTabla( request.getParameter("idbean") );
			
			forward = "gridpojo2";
		}
		
		
		pojo.setUrlAlta("genericABC.do?accion=alta");
		pojo.setUrlBaja("genericABC.do?accion=eliminar");
		pojo.setUrlCambios("genericABC.do?accion=editaObjeto");

		request.setAttribute("griPojo", pojo);
		return mapping.findForward(forward);
		
	}

}
